<template>
    <div class="weui-tab">
        <div class="iframe">
            <ActivateDevice @state="state" v-if="page === 'activate_device'" :sn="m_page"></ActivateDevice>
            <AddDevice @state="state" v-if="page === 'add_device'" :content="m_page"></AddDevice>
            <Demo @state="state" v-if="page === 'demo'" :userInfo="userInfo" :devices="devices"></Demo>
            <EquipmentList @state="state" v-if="page === 'equipment_list'" :content="m_page"></EquipmentList>
            <Example @state="state" v-if="page === 'example'" :content="m_page"></Example>
            <Record @state="state" v-if="page === 'record'" :debug="debug" :userInfo="userInfo" :devices="devices"
                    :talk_list="talk_list"></Record>
            <ViewDevice ref="ViewDevice" @state="state" v-if="page === 'view_device'" :geoc="geoc" :userInfo="userInfo"
                        :devices="devices" :ps_img="ps_img"></ViewDevice>
            <DeviceMap ref="DeviceMap" @state="state" v-if="page === 'device_map'" :geoc="geoc" :sn="userInfo['ctl']"
                       :device="devices[userInfo['ctl']]"></DeviceMap>
        </div>
        <Audio style="height: 0;opacity: 0" id="audio1"></Audio>
        <div class="weui-tabbar" style="position: relative;height: 8vh;">
            <div class="weui-tabbar__item" style="padding: 0;" v-for="(button, index) in buttons"
                 @click="setPage(index)">
                <img style="height: 4vh" :src="activeIndex === index ? button.img_click:button.img_un_click "/>
                <p class="weui-tabbar__label" :style="activeIndex === index ? 'color:#444':'' ">{{button.img_text}}</p>
            </div>
        </div>
    </div>
</template>

<script>
    import ActivateDevice from './components/ActivateDevice';
    import AddDevice from './components/AddDevice';
    import Demo from './components/Demo';
    import DeviceMap from './components/DeviceMap';
    import EquipmentList from './components/EquipmentList';
    import Example from './components/Example';
    import Record from './components/Record';
    import ViewDevice from './components/ViewDevice';
    import {getCookie, htmlDecodeByRegExp, http, send} from "../static/js/common";

    export default {
        components: {
            ActivateDevice, AddDevice, Demo, DeviceMap, EquipmentList, Example, Record, ViewDevice,
        },
//        comments: {
//            'device_map': DeviceMap
//        },
        name: 'App',
        data() {
            return {
                ps_img: '',
                debug: false,
                opacity: this.page === 'device_map' ? 'opacity:1' : 'opacity:0',
                activeIndex: 0,
                buttons: [
                    {
                        img_click: 'http://weixin.pbani.com/wx/static/images/location_on.png',
                        img_un_click: 'http://weixin.pbani.com/wx/static/images/location.png',
                        img_text: '定位轨迹',
                        page: 'device_map',
                    },
                    {
                        img_click: 'http://weixin.pbani.com/wx/static/images/mng_on.png',
                        img_un_click: 'http://weixin.pbani.com/wx/static/images/mng.png',
                        img_text: '功能管理',
                        page: 'view_device',
                    },
                    {
                        img_click: 'http://weixin.pbani.com/wx/static/images/msg_on.png',
                        img_un_click: 'http://weixin.pbani.com/wx/static/images/msg.png',
                        img_text: '收发消息',
                        page: 'record',
                    },
                ],
                // geoc: new BMap.Geocoder(),
                geoc: null,
                devices: {},
                m_page: '',
                frame: $('.iframe'),
                m_userInfo: {},
                talk_list: []
            }
        },
        computed: {
            page: {
                get() {
                    return this.m_page;
                },
                set(page) {
                    console.log(page);
                    // alert(page)
//                    console.log(this.$refs[page]);
//                    this.$refs[page].init();
                    this.m_page = page;
                }
            },
            userInfo: {
                get() {
                    return this.m_userInfo;
                },
                set(userInfo) {
                    this.m_userInfo = userInfo;
                    if (userInfo.hasOwnProperty('devices')) {
                        let device_arr = [];
                        for (let device in userInfo['devices']) {
                            if (userInfo['devices'].hasOwnProperty(device)) {
                                device_arr.push(device);
                                if (!this.devices[device]) {

                                    http({
                                        url: `get_device_info`,
                                        param: {
                                            sn: device
                                        }
                                    }).then(data => {
                                        this.$set(this.devices, device, data.info);
                                        http({
                                            url: "location",
                                            param: {
                                                'device_type': device['type'],
                                                'sn': device
                                            }
                                        }).then(data => {});
                                    })
                                }
                            }
                        }
                        for (let device in this.devices) {
                            if (this.devices.hasOwnProperty(device)) {
                                if (device_arr.indexOf(device) === -1) {
                                    delete this.devices[device]
                                }
                            }
                        }
                    }
                }
            }
        },
        methods: {
            state(data) {
                let key;
                for (key in data) {
                    if (data.hasOwnProperty(key)) {
                        if (typeof data[key] === 'object') {
                            data[key] = JSON.parse(JSON.stringify(data[key]))
                        }
                        this[key] = data[key]
                    }

                }
            },
            setPage(index) {
                this.activeIndex = index;
                this.page = this.buttons[this.activeIndex].page;
            },
            getUserInfo() {
                http({
                    url: `get_user_info`,
                    param: {}
                }).then(data => {
                    this.userInfo = data.info;
                    // alert(data.page)
                    // this.m_page = data.page;
                    // this.m_page = 'view_device';
                    this.m_page = page_action || 'view_device';
                    this.initSocket();
                });
            },
            firstLoad() {
                if (location.host.split(':').length > 1) {
                    console.log('test');
                    http({
                        url: `login_for_test`,
                        param: {
                            action: location.hash.split('/')[1] || 'view_device'
                        }
                    }).then(data => {
                        this.getUserInfo()
                    });
                } else {
                    this.getUserInfo()
                }

                this.frame.css('height', this.frame.height())
            },
            initSocket() {
                // let url = this.debug ? (`ws://127.0.0.1/chat`) : (`ws://weixin.pbani.com/chat`);
                // console.log(url)
                // window.socket = io.connect(`${url}`, {
                //     transports: ['websocket']
                // });

                let namespace = '/chat';
                // let url = this.debug ? (`http://127.0.0.1${namespace}`) : (`http://weixin.pbani.com${namespace}`);
                let url = `http://weixin.pbani.com${namespace}`;

                console.log("oooooooopPPPPPPPPPPPPPPP");
                console.log(url);

                window.socket = io.connect(`${url}`);
                let event_arr = {
                    'to_join': () => {
                        window.socket.emit('join', {
                            'id': this.userInfo.openid
                        })
                    },
                    'test': () => {
                        $.alert('test')
                    },
                    'set_model': (data) => {
                        this.$refs.ViewDevice.set_model(data);
                    },
                    'upload_voice_msg': (url) => {
                        console.log(`upload_voice_msg (${url})`);
                        let music = new Audio();
                        if (!url.startsWith('http')) {
                            music.src = 'http://' + url;
                        } else {
                            music.src = url;
                        }
                        music.play();
                    },
                    'upload_ps': (url) => {
                        this.ps_img = 'http://' + url
                    },
                    'connect': function () {
                        console.log('web connected')
                    },
                    'self_message': (data) => {
                        if (this.page === 'record') {
                            console.log(data);
                            this.talk_list.push(data);
                        }
                    },
                    'location_upload': () => {
                        if (this.page === 'device_map') {
                            this.$refs.DeviceMap.location();
                        }
                    },
                    'device_message': (data) => {
                        if (this._page === 'record') {
                            console.log(data);
                            this.talk_list.push(data);
                        } else {
                            $.alert("注意", "您有新的消息，请注意查收。", () => {
                                this._page = 'record';
                            });
                        }
                    }
                };

                let event;
                for (event in event_arr) {
                    (function (event) {
                        window.socket.on(event, function () {
                            console.log(`trigger event (${event})`);
                            event_arr[event](...arguments);
                        });
                    })(event);
                }

                $(window).unload(() => {
                    send('leave');
                    window.socket.emit('leave', this.userInfo.openid, () => {
                        console.log(`${this.userInfo.openid} leave`)
                    })
                });
            },
            initWx() {
                http({
                    url: `get_signature`,
                    param: {
                        url: location.href
                    }
                }).then(data => {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: data.appId, // 必填，公众号的唯一标识
                        timestamp: data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: data.nonceStr, // 必填，生成签名的随机串
                        signature: data.signature, // 必填，签名，见附录1
                        jsApiList: ['scanQRCode', 'startRecord', 'stopRecord', 'playVoice', 'uploadVoice', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    });
                    wx.ready(() => {
                        console.log('wx ready')
//                        wx_ready = true;
                    });
                    wx.error((res) => {
                        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                        console.log(res);
                    });
                });
            }
        },
        created() {
            if (location.href.indexOf('127.0.0.1') !== -1) {
                this.debug = true;
            }
            this.initWx();
        },
        mounted() {
            this.firstLoad();
        }
    }
</script>

<style scoped>
    .demos-title {
        text-align: center;
        font-size: 34px;
        color: #3cc51f;
        font-weight: 400;
        margin: 0 15%;
    }

    .demos-sub-title {
        text-align: center;
        color: #888;
        font-size: 14px;
    }

    .demos-header {
        padding: 35px 0;
    }

    .demos-content-padded {
        padding: 15px;
    }

    .demos-second-title {
        text-align: center;
        font-size: 24px;
        color: #3cc51f;
        font-weight: 400;
        margin: 0 15%;
    }

    footer {
        text-align: center;
        font-size: 14px;
        padding: 20px;
    }

    footer a {
        color: #999;
        text-decoration: none;
    }

    .weui-tabbar__label {
        color: #27AF9F;
    }

    .weui-tabbar__item.weui-bar__item--on .weui-tabbar__label {
        color: #E3767D;
    }

    .iframe {
        width: 100%;
        height: 91.5vh;
        position: relative;
        overflow: scroll;
    }
</style>
